<?php

namespace app\controller;

use app\BaseController;
use Lib\Crypt;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\response\Json;

class Admin extends BaseController
{
    /**
     * 切换联机权限
     */
    public function Online(): Json
    {
        if (!$this->checkAuth()) return pr(300, API_NO_AUTH);
        $uid = $this->request->post('uid', 0, 'int');
        $stat = $this->request->post('stat', 0, 'int');
        $this->writeLog("切换联机权限","切换用户[" . $uid . "]联机权限为[" . $stat . "]");
        $this->M('user')->where(['id', '=', $uid])->save(['account_type' => $stat]);
        return pr(200);
    }
    public function writeLog($method,$state){
        //记录调用日志
        $this->M('log_admin')->insert(['uid' => $this->getUid(), 'ip' => getUserIp(), 'time' => time(), 'method' => $method, 'state' => $state]);
        \think\facade\Log::write($method.$state);
    }

    /**
     * 是否为管理员
     */
    private function checkAuth($isDevelopers = false,$uid1 = null): bool
    {
        if (!empty($uid1)) $uid = $uid1;
        else $uid = $this->getUid();
        if (empty($uid)) return false;
        try {
            if(!empty($isDevelopers))$check = $this->M('user_role')->where('uid', '=', $uid)->where('role_id', '=', 2)->find();
            else $check = $this->M('user_role')->where('uid', '=', $uid)->where('role_id', '=', 1)->find();
            if (empty($check)) return false; else return true;
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            return false;
        }
    }

    /**
     * 上次QQ群QQ列表
     */
    public function UploadQQ($data): Json
    {
        if (!$this->checkAuth()) return pr(300, API_NO_AUTH);
        $data = json_decode($data, true);
        if (empty($data)) return pr(300, "数据为空");
        $this->M('wardroom_qq')->insertAll($data);
        return pr(200);
    }

    /**
     * 获取邀请码使用情况
     */
    public function getInviteCode(): Json
    {
        if (!$this->checkAuth()) return pr(300, API_NO_AUTH);
        $page = request()->post('page');
        $limit = request()->post('limit');
        $search = request()->post('search');
        $search_type = request()->post('search_type', 0, 'int'); //0 用户名 1 邮箱 2 昵称
        try {
            $sum = 0;
            $obj = $this->M('invitation_used')->alias("ic")->field("ic.*,iic.*,u.account,u.nickname");
            if (!empty($search)) {
                switch ($search_type) {
                    case 1:
                        $obj->where('u.nickname', 'like', '%' . $search . '%');
                        break;
                    case 2:
                        $obj->where('u.email', 'like', '%' . $search . '%');
                        break;
                    default:
                        $obj->where('u.account', 'like', '%' . $search . '%');
                        break;
                }
            }
            $obj->leftJoin("user u", "u.id = ic.uid");
            $obj->leftJoin("invitation_code iic", "iic.id = ic.iid");


            if ($page == 1) $sum = $obj->count();
            $obj->page($page, $limit);
            $list = $obj->select()->toArray();
            $list['_extra'] = ['sum' => $sum];
            return pr(200, API_SUCCESS, $list);
        } catch (DbException $e) {
            return pr(301, API_DB_ERROR);
        }
    }

    /**
     * 刷新点赞数量 【频繁读写数据库！】
     */
    public function refreshGood(): Json
    {
        if (!$this->checkAuth()) return pr(300, API_NO_AUTH);
        $list = $this->M('bbs_good')->field('bid,count(*) as count')->group('bid')->select()->toArray();
        foreach ($list as $v) {
            $this->M('bbs')->where('id', '=', $v['bid'])->save(['good_num' => $v['count']]);
        }
        $list = $this->M('bbs_reply_good')->field('rid,count(*) as count')->group('rid')->select()->toArray();
        foreach ($list as $v) {
            $this->M('bbs_reply')->where('id', '=', $v['rid'])->save(['good_num' => $v['count']]);
        }
        return pr(200, API_SUCCESS);
    }

    /**
     * 用户列表
     */
    public function member_list(): Json
    {
        $page = request()->post('page');
        $limit = request()->post('limit');
        $conditions = request()->post('conditions');
        $token = request()->post('token');
        if (empty($token)) {
            $uid = $this->getUid();
        } else {
            $uid = $this->M('user')->where(['token' => $token])->value('id');
        }
        if (empty($uid)) return pr(302, API_NEED_LOGIN);
        if (!$this->CheckAuthority($uid, "账户管理")) return pr(300, API_NO_AUTH);
        // if (!$this->checkAuth(false, $uid)) return pr(300, API_NO_AUTH);
    
        try {
            $sum = 0;
            $obj = $this->M('user')->alias("u")
                ->field("u.*, group_concat(ur.role_id) as role_list")
                ->leftJoin("user_role ur", "ur.uid = u.id");
            // 搜索start
            $conditionsList = array(
                0 => array("field" => "u.id", "match" => "="), // id
                1 => array("field" => "u.nickname", "match" => "like"), // 昵称
                2 => array("field" => "u.account", "match" => "like"), // 账号
                3 => array("field" => "u.stat", "match" => "like"), // 状态
                4 => array("field" => "u.last_login_ip", "match" => "like"), // 登录ip,
                5 => array("field" => "ur.role_id", "match" => "="), // 头衔
                6 => array("field" => "u.remark", "match" => "like") // 备注
            );
    
            if (!empty($conditions) && count($conditions) > 0) {
                foreach ($conditions as $v) {
                    if (is_numeric($v['type']) && $v['type'] >= 0 && $v['type'] <= count($conditionsList) - 1) {
                        $conObj = $conditionsList[$v['type']];
                        if ($conObj['field'] == "u.remark" && $v['value'] === '*') {
                            // 过滤掉 remark 为 '' 的选项
                            $obj = $obj->where($conObj['field'], '<>', '');
                            
                        } else {
                            if ($conObj['match'] == "like") {
                                $obj = $obj->where($conObj['field'], 'like', '%' . $v['value'] . '%');
                            } else {
                                $obj = $obj->where($conObj['field'], $conObj['match'], $v['value']);
                            }
                        }
                    }
                }
            }
            // 搜索End
            $obj = $obj->group("u.id");
            $obj->order('u.id', 'desc');
            if ($page == 1) $sum = $obj->count();
            $obj->page($page, $limit);
            $list = $obj->select()->toArray();
            $list['_extra'] = ['sum' => $sum];
            return pr(200, API_SUCCESS, $list);
        } catch (DbException $e) {
            return pr(301, API_DB_ERROR);
        }
    }


    /**
     * 资源列表
     */
    public function mod_list(): Json
    {
        $page = request()->post('page');
        $limit = request()->post('limit');
        $conditions = request()->post('conditions');
        if(!$this->CheckAuthority($this->getUid(), "资源管理"))  return pr(300, API_NO_AUTH);
        //if (!$this->checkAuth()) return pr(300, API_NO_AUTH);
        try {
            $sum = 0;
            $obj = $this->M('mod');
             //搜索Start
           $conditionsList = array(
                0=>array("field"=>"name","match"=>"like"), //名称
                1=>array("field"=>"package_id","match"=>"like"), //mod标识
                2=>array("field"=>"stat","match"=>"="), //状态
                3=>array("field"=>"uid","match"=>"=") //用户id
            );
           if (!empty($conditions) && count($conditions) > 0) {
                foreach($conditions as $v){
                    if(is_numeric($v['type']) && $v['type'] >= 0 && $v['type'] <= count($conditionsList) - 1){
                        $conObj = $conditionsList[$v['type']];
                        if($conObj['match'] == "like"){
                            $obj = $obj->where($conObj['field'], 'like', '%' . $v['value'] . '%');
                        } else{
                            $obj = $obj->where($conObj['field'], $conObj['match'], $v['value']);
                        }
                    }
                }
            } 
            //搜索End
            $obj->order('last_modify_time', 'desc');
            if ($page == 1) $sum = $obj->count();
            $obj->page($page, $limit);
            $list = $obj->select()->toArray();
            $list['_extra'] = ['sum' => $sum];
            return pr(200, API_SUCCESS, $list);
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            return pr(301, API_DB_ERROR);
        }
    }

      /**
     * 服列表
     */
    public function server_list(){
        $page = request()->post('page');
        $limit = request()->post('limit');
        $conditions = request()->post('conditions');
        //if (!$this->checkAuth()) return pr(300, API_NO_AUTH);
        if(!$this->CheckAuthority($this->getUid(), "服列表管理"))  return pr(300, API_NO_AUTH);
        try {
            $sum = 0;
            $obj = $this->M("mod_server_detail")
                ->alias('msd')
                 ->field("msd.id as sd_id,msd.mod_id,msd.ip_addr as ip,svl.version,msd.last_modify_time as time,msd.name,msd.level,msd.stat,sm.description,sm.uid,u.nickname as uname")
                ->join("mod sm",'sm.id = msd.mod_id')
                ->leftJoin("user u", "u.id = sm.uid")
                ->leftJoin("server_version_list svl", "svl.id = msd.version_id");
            $obj = $obj->where('msd.stat', '<>', 2);
            //搜索Start
           $conditionsList = array(
                0=>array("field"=>"msd.name","match"=>"like"), //名称
                1=>array("field"=>"msd.ip_addr","match"=>"like"), //ip
                2=>array("field"=>"msd.level","match"=>"="), //等级
                3=>array("field"=>"msd.stat","match"=>"="), //状态
                4=>array("field"=>"svl.version","match"=>"like") //版本
            );
           if (!empty($conditions) && count($conditions) > 0) {
                foreach($conditions as $v){
                    if(is_numeric($v['type']) && $v['type'] >= 0 && $v['type'] <= count($conditionsList) - 1){
                        $conObj = $conditionsList[$v['type']];
                        if($conObj['match'] == "like"){
                            $obj = $obj->where($conObj['field'], 'like', '%' . $v['value'] . '%');
                        } else{
                            $obj = $obj->where($conObj['field'], $conObj['match'], $v['value']);
                        }
                    }
                }
            } 
            //搜索End
            $obj->order('msd.last_modify_time', 'desc');
            if ($page == 1) $sum = $obj->count();
            $obj->page($page, $limit);
            $list = $obj->select()->toArray();
            $list['_extra'] = ['sum' => $sum];
            return pr(200, API_SUCCESS, $list);
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            return pr(301, API_DB_ERROR);
        }
    }

    //服列表状态修改
    public function update_server_state(){
        //if (!$this->checkAuth()) return pr(300, API_NO_AUTH);
        if(!$this->CheckAuthority($this->getUid(), "服列表管理"))  return pr(300, API_NO_AUTH);
        $sd_id = request()->post('sd_id');
        $stat = request()->post('stat');
        $this->M('mod_server_detail')->where(['id'=>$sd_id])->update(['stat'=>$stat]);
        return pr(200, API_SUCCESS);
    }

    /**
     * 版本列表
     */
    public function version_list(): Json
    {
        $page = request()->post('page', 1, 'int');
        $limit = request()->post('limit', 10, 'int');
        $id = request()->post('id', 0, 'int');
        $type = request()->post('type', 0, 'int');
        $operate = request()->post('operate', 0, 'int');
        $name = request()->post('name');
        $version = request()->post('version');
        if (!$this->checkAuth()) return pr(300, API_NO_AUTH);
        switch ($type) {
            case 1:
                $tableName = "api_version_list";
                break;
            case 2:
                $tableName = "game_version_list";
                break;
            case 3:
                $tableName = "server_version_list";
                break;
            default:
                break;
        }
        $model = $this->M($tableName);
        switch ($operate) {
            //查询列表
            case 0:
                $list = $model->page($page, $limit)->select()->toArray();
                return pr(200, API_SUCCESS, $list);
            //编辑列表
            case 1:
                if (empty($id)) return pr(300, '参数不可为空');
                if (empty($name) || empty($version)) return pr(300, '名称或版本不能为空');
                $model->where('id', '=', $id)->save(['name' => $name, 'version' => $version]);
                return pr(200);
            //添加内容
            case 2:
                if (empty($name) || empty($version)) return pr(300, '名称或版本不能为空');
                $model->insert(['version' => $version, 'name' => $name]);
                return pr(200);
            default:
                break;
        }
        return pr(300, 'unknown type ' . $operate);

    }

    public function examine_mod(): Json
    {
        //if (!$this->checkAuth()) return pr(300, API_NO_AUTH);
        if(!$this->CheckAuthority($this->getUid(), "资源管理"))  return pr(300, API_NO_AUTH);
        $id = $this->request->post('id');
        $stat = $this->request->post('stat');
        $reason = $this->request->post('reason');
        $this->M("mod")->where('id', '=', $id)->save(['stat' => $stat, 'reason' => $reason]);
        $this->writeLog("审核资源", "审核资源ID[" . $id . "].状态[" . $stat . "]");
        return pr(200);

    }

    /**
     * 帖子列表
     */
    public function bbs_list(): Json
    {
        $page = request()->post('page');
        $limit = request()->post('limit');
        $search = request()->post('search');
        $search_type = request()->post('search_type', 0, 'int'); //0搜标题和内容 1帖子id 2用户id
        //if (!$this->checkAuth()) return pr(300, API_NO_AUTH);
        if(!$this->CheckAuthority($this->getUid(), "资源管理"))  return pr(300, API_NO_AUTH);
        try {
            $sum = 0;
            $obj = $this->M('bbs');
            if (!empty($search)) {
                switch ($search_type) {
                    case 0:
                        $obj->whereOr([[['title', 'like', '%' . $search . '%']], [['content', 'like', '%' . $search . '%']],]);
                        break;
                    case 1:
                        $obj->where('id', 'like', '%' . $search . '%');
                        break;
                    case 2:
                        $obj->where('uid', 'like', '%' . $search . '%');
                        break;
                }
                
            } else {
                $obj->order('id', 'desc');
            }
            if ($page == 1) $sum = $obj->count();
            
            $obj->page($page, $limit);
            $list = $obj->select()->toArray();
            $list['_extra'] = ['sum' => $sum];
            return pr(200, API_SUCCESS, $list);
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            return pr(303, API_DB_ERROR);
        }
    }

    /**
     * 头衔列表
     */
    public function role_list(): Json
    {
        $page = request()->post('page',1);
        $limit = request()->post('limit',10);
        $all = request()->post('all',0);
        $token = request()->post('token');
        if (empty($token)) {
            $uid = $this->getUid();
        } else {
            $uid = $this->M('user')->where(['token' => $token])->value('id');
        }
        //if (!$this->checkAuth())  return pr(300, API_NO_AUTH);
        if(!$this->CheckAuthority($uid, "账户管理"))  return pr(300, API_NO_AUTH);
        try {
            $sum = 0;
            $obj = $this->M('role_list');
            if ($page == 1) $sum = $obj->count();
            if($all==1){
                $list = $obj->select()->toArray();
            }else{
                $list = $obj->page($page, $limit)->select()->toArray();
            }
            $list['_extra'] = ['sum' => $sum];
            return pr(200, API_SUCCESS, $list);
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            return pr(303, API_DB_ERROR);
        }
    }

    /**
     * 添加头衔
     */
    public function add_role(): Json
    {
        //if (!$this->checkAuth()) return pr(300, API_NO_AUTH);
        if(!$this->CheckAuthority($this->getUid(), "账户管理"))  return pr(300, API_NO_AUTH);
        $name = $this->request->post('name');
        $color = $this->request->post('color');
        $type = $this->request->post('type');
        $effect = $this->request->post('effect');
        $id = $this->request->post('id', 0, 'int');
        //记录调用日志
        $this->writeLog("添加头衔", "添加头衔[" . $name . "]");
        if ($id > 0) {
            $this->M("role_list")->where('id', '=', $id)->save(['name' => $name, 'color' => $color, 'type' => $type, 'effect' => $effect]);
        } else {
            $this->M("role_list")->insert(['name' => $name, 'color' => $color, 'type' => $type, 'effect' => $effect]);
        }
        return pr(200);

    }

    /**
     * 添加板块
     */
    public function add_cate(): Json
    {
        if (!$this->checkAuth()) return pr(300, API_NO_AUTH);
        $introduce = $this->request->post('introduce');
        $name = $this->request->post('name');
        $id = $this->request->post('id', 0, 'int');
        //记录调用日志
        $this->writeLog("添加板块", "添加板块[" . $name . "]");
        if ($id > 0) {
            $this->M("category")->where('id', '=', $id)->save(['name' => $name, 'introduce' => $introduce]);
        } else {
            $this->M("category")->insert(['name' => $name, 'introduce' => $introduce]);
        }
        return pr(200);

    }

    /**
     * 板块列表
     */
    public function cate_list(): Json
    {
        $page = request()->post('page');
        $limit = request()->post('limit');
        if (!$this->checkAuth()) return pr(300, API_NO_AUTH);
        try {
            $sum = 0;
            $obj = $this->M('category');
            if ($page == 1) $sum = $obj->count();
            $list = $obj->page($page, $limit)->select()->toArray();
            $list['_extra'] = ['sum' => $sum];
            return pr(200, API_SUCCESS, $list);
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            return pr(303, API_DB_ERROR);
        }
    }

    /*
     * 修改用户备注、修改用户信息
     */
    public function edit_user(): Json
    {
        //if (!$this->checkAuth()) return pr(300, API_NO_AUTH);
        if(!$this->CheckAuthority($this->getUid(), "账户管理"))  return pr(300, API_NO_AUTH);
        $id = $this->request->post('id', 0, 'int');
        $remark = $this->request->post('remark');
        $nickname = request()->post('nickname');
        $email = request()->post('email');
        $avatar = request()->post('avatar');
        $signature = request()->post('signature');
        $background = request()->post('background');
        $newPass = request()->post('newPass');
        $data = [];

        if (!empty($nickname)) {
            $name = $this->M('user')->where(['nickname' => $nickname])->value('nickname');
            if ($name == $nickname) {
                return pr(300, "该昵称已被使用");
            }
            $data['nickname'] = $nickname;
        }
        if (!empty($email)) {
            $email1 = $this->M('user')->where(['email' => $email])->value('email');
            if ($email1 == $email) {
                return pr(300, "该邮箱已被使用");
            }
            $data['email'] = $email;
        }
        if (!empty($remark)) $data['remark'] = $remark;
        if (!empty($avatar)) $data['head_img'] = $avatar;
        if (!empty($signature)) $data['signature'] = $signature;
        if (!empty($background)) $data['background'] = $background;
        if (!empty($newPass)) {
            $data['password'] = Crypt::Encode($newPass);
            $data['token'] = makeAccessToken();
        }
        //记录调用日志
        $this->writeLog("修改用户信息", "修改用户[" . $id . "]信息".json_encode($data));
        $this->M('user')->where('id', '=', $id)->update($data);
        return pr(200);
    }

    /**
     * 锁锭任务
     * @return void
     */
    public function lock_item(): Json
    {
        $checkAuthority = false;
        //if (!$this->checkAuth()) return pr(300, API_NO_AUTH);
        $id = $this->request->post('id', 0, 'int');
        $stat = $this->request->post('stat', 0, 'int');
        $type = $this->request->post('type', 0, 'int');
        $table = "";
        switch ($type) {
            case 1:
                $table = "user";
                $method="用户";
                $checkAuthority = $this->CheckAuthority($this->getUid(), "账户管理");
                break;
            case 2:
                $table = "bbs";
                $method="帖子";
                $checkAuthority = $this->CheckAuthority($this->getUid(), "资源管理");
                break;
            case 3:
                $table = "mod";
                $method="资源";
                $checkAuthority = $this->CheckAuthority($this->getUid(), "资源管理");
                break;
            case 4:
                $table = "role_list";
                $method="头衔";
                $checkAuthority = $this->CheckAuthority($this->getUid(), "账户管理");
                break;
            case 5:
                $table = "category";
                $method="板块";
                $checkAuthority = $this->CheckAuthority($this->getUid(), "资源管理");
                break;
        }
        if(!$checkAuthority) return pr(300, API_NO_AUTH);
        if (empty($table)) return pr(300, "未知类型");
        if (empty($method)) return pr(300, "未知类型");
        $this->M($table)->where('id', '=', $id)->save(['stat' => $stat]);
        $state = ($stat == 0 ? '锁定' : '解锁').$method;
        //记录调用日志
        $this->writeLog($state,  $state."对象ID[" . $id . "]");
        return pr(200,$state , ['stat' => $stat]);
    }

    /**
     * 删除任务
     * @return void
     * @throws DbException
     */
    public function del_item(): Json
    {
        if (!$this->checkAuth()) return pr(303, API_NO_AUTH);
        $id = $this->request->post('id', 0, 'int');
        $type = $this->request->post('type', 0, 'int');
        $code = "300";
        $msg="删除失败";
        $result = false;
        switch ($type) {
            case 1:
                $table = "user";
                break;
            case 2:
                //删除帖子
                $this->M("bbs_good")->where('bid',$id)->delete();
                $rl = $this->M("bbs_reply")->where('bid',$id)->field('id')->select()->toArray();
                $this->M("bbs_reply")->where('bid',$id)->delete();
                $ll = [];
                foreach ($rl as $v)$ll[] = $v['id'];
                $this->M("bbs_reply_good")->where('rid','in',$ll)->delete();
                $this->M("bbs")->where('id', '=', $id)->delete();
                $result = true;
                $code=200;
                $msg="删除帖子成功";
                break;
            case 3:
                $table = "mod";
                break;
            case 4:
                $table = "role_list";
                break;
            case 5:
                $table = "category";
                break;
        }
        if (!$result) return pr(300, "未知类型");
        $this->writeLog("删除类型[".$type."]",  "删除对象ID[" . $id . "]");
        return pr($code,  $msg);
    }

    public function server_info(): Json
    {
        try {
            $userCount = $this->M("user")->count();
            $modCount = $this->M("mod")->count();
            $bbsCount = $this->M("bbs")->count();
            return pr(200, API_SUCCESS, ['member' => $userCount, 'mod' => $modCount, 'bbs' => $bbsCount]);
        } catch (DbException $e) {
            return pr(300);
        }
    }

    /**
     * 设置用户头衔，先用着，等待重构
     */
    public function set_user_role(): Json
    {
        //if (!$this->checkAuth(true)) return pr(300, API_NO_AUTH);
        $roleList = $this->request->post('role_list');
        $uid = $this->request->post('uid');
        $roleList = json_decode($roleList, true);
        $operatorAuthorityLevel = $this->GetAuthorityLevel($this->getUid());
        $targetAuthorityLevel = $this->GetAuthorityLevel($uid);
        if($operatorAuthorityLevel < 50) return pr(300, API_NO_AUTH); //操作者不是（总）管理/开发/账户管理，无法修改
        if($operatorAuthorityLevel <= $targetAuthorityLevel) return pr(300, API_NO_AUTH); //操作者权限等级小于或等于操作对象权限等级时，无法修改
        try {
            $this->M("user_role")->where('uid', '=', $uid)->delete();
            $insert = [];
            $pass = true;
            foreach ($roleList as $v) {
                if(($operatorAuthorityLevel == 99) && ($v == 1 || $v == 2)){ //操作者为（总）管理时，不能给其他人设置（总）管理、开发
                    $pass = false;
                }
                if(($operatorAuthorityLevel == 50) && in_array($v,[1, 2, 13, 14, 16, 17, 18]) ){ //操作者为账户管理时，不能给其他人设置管理、开发
                    $pass = false;
                }
                $insert[] = ['uid' => $uid, 'role_id' => $v];
            }
            if(!$pass) return pr(300, API_NO_AUTH);
            $this->M("user_role")->insertAll($insert);
            //记录调用日志
            $this->writeLog("设置用户头衔","对象用户ID[".$uid."]".json_encode($roleList));
            return pr(200);
        } catch (DbException $e) {
            return pr(301);
        }
    }

    /**
     * 游戏内公告
     */
    public function get_site_config(): Json
    {
        //if (!$this->checkAuth()) return pr(300, API_NO_AUTH);
        if(!$this->CheckAuthority($this->getUid(), "公告管理"))  return pr(300, API_NO_AUTH);
        $config = $this->M('config')->select();
        return pr(200, API_SUCCESS, $config);
    }

    /**
     * 设置游戏内公告
     */
    public function save_site_config(): Json
    {
        $config = request()->post('config');
        $config = json_decode($config, true);
        if(!$this->CheckAuthority($this->getUid(), "公告管理"))  return pr(300, API_NO_AUTH);
        //if (!$this->checkAuth()) return pr(300, API_NO_AUTH);
        foreach ($config as $v) {
            $this->M('config')->where('id', '=', $v['id'])->update(['value' => $v['value']]);
        }
        //记录调用日志
        $this->writeLog("设置游戏内公告",  "设置游戏内公告".json_encode($config));
        return pr(200);
    }

    //获取权限等级
    private function GetAuthorityLevel($uid): int
    {
        $authorityLevel = -1;
        if (empty($uid)) return $authorityLevel;
        try {
            $roleList = $this->M('user_role')->where('uid', '=', $uid)->select()->toArray();
            if (empty($roleList)) return $authorityLevel;
            foreach($roleList as $v){
                $level = 0;
                switch($v["role_id"]){
                    case 2: $level = 999; break; //开发者
                    case 1: $level = 99; break; //总管理
                    case 18: $level = 50; break; //账户管理
                    case 17: $level = 8; break; //公告管理
                    case 16: $level = 7; break; //服列表管理
                    case 13: $level = 6; break; //资源（帖子）管理
                    case 14: $level = 1; break; //轮值管理
                }
                if($level > $authorityLevel) $authorityLevel = $level;
            }
            return $authorityLevel;
        } catch (DataNotFoundException | ModelNotFoundException | DbException $e) {
            return $authorityLevel;
        }
    }

     //检查权限
     private function CheckAuthority($uid, $type): bool
     {
        if (empty($uid)) return false;
        try {
            $roleList = $this->M('user_role')->where('uid', '=', $uid)->select()->toArray();
            if (empty($roleList)) return false;
            foreach($roleList as $v){
                if($v["role_id"] == 1 || $v["role_id"] == 2) return true;
                switch($type){
                    case "账户管理": if($v["role_id"] == 18) return true; break;
                    case "公告管理": if($v["role_id"] == 17) return true; break;
                    case "服列表管理": if($v["role_id"] == 16) return true; break;
                    case "资源管理": if($v["role_id"] == 13) return true; break;
                    case "轮值管理": if($v["role_id"] == 14) return true; break;
                }
            }
            return false;
        } catch (DataNotFoundException | ModelNotFoundException | DbException $e) {
            return false;
        }
     }
}
